package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.JsonUtil;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.enums.FarmRecordsTableEnum;
import com.dongjiantong.farmrecords.mapper.FarmRecordsDrugsMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFileMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsDrugs;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.service.FarmRecordsDrugsService;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.sys.enums.LogsEnum;
import com.dongjiantong.sys.service.SysLogsService;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 生产中心 -- 兽药记录
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsDrugsServiceImpl extends ServiceMybatis<FarmRecordsDrugs> implements FarmRecordsDrugsService {

    @Resource
    private FarmRecordsDrugsMapper farmRecordsDrugsMapper;
    @Resource
    private FarmRecordsFileMapper farmRecordsFileMapper;

    @Resource
    public FarmRecordsFileService farmRecordsFileService;

    @Reference(version = "1.0.0")
    public SysLogsService sysLogsService;


    @Override
    public PageInfo<FarmRecordsDrugs> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsDrugsMapper == null){
                throw new OPServerException("farmRecordsDrugsMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsDrugs> farmRecordsDrugsList = farmRecordsDrugsMapper.selectByMap(map);
            if (farmRecordsDrugsList.size() > 0){
                this.setPicOrVideoList(farmRecordsDrugsList);
            }
            return new PageInfo<FarmRecordsDrugs>(farmRecordsDrugsList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 设置关联信息(视频,图片)
     * @param farmRecordsDrugsList
     */
    public void setPicOrVideoList(List<FarmRecordsDrugs> farmRecordsDrugsList){
        if (farmRecordsFileMapper == null){
            throw new OPServerException("farmRecordsFileMapper 为null,请检查");
        }
        List<Long> ids = farmRecordsDrugsList.stream().map(farmRecordsDrugs -> farmRecordsDrugs.getId()).collect(Collectors.toList());

        List<Integer> type2List = Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode());

        Map map = Maps.newHashMap();
        map.put("relevanceIds",ids);
        map.put("listType2",type2List);
        map.put("type1",FarmRecordsFileEnum.DRUG.getCode());
        //查询对应的图片,视频
        List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileMapper.selectPicOrVideoListByRelevanceIds(map);

        if (farmRecordsFileList.size() > 0){
            for (FarmRecordsDrugs farmRecordsDrugs : farmRecordsDrugsList){
                this.setPicOrVideoByObject(farmRecordsDrugs,farmRecordsFileList);
            }
        }
    }

    /**
     * 放入图片 视频到对象中
     * @param farmRecordsDrugs
     * @param farmRecordsFileList
     */
    @Override
    public FarmRecordsDrugs setPicOrVideoByObject(FarmRecordsDrugs farmRecordsDrugs, List<FarmRecordsFile> farmRecordsFileList) {
        List<String> picList = null;
        List<String> videoList = null;
        for (FarmRecordsFile farmRecordsFile : farmRecordsFileList){
            if ((farmRecordsDrugs.getId()).equals(farmRecordsFile.getRelevance_id())){
                //获取图片
                if ((FarmRecordsFileEnum.PHOTO.getCode()).equals(farmRecordsFile.getType2())){
                    JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                    List<String> list = jsonArray.toJavaList(String.class);
                    picList = list;
                }
                //获取视频
                if ((FarmRecordsFileEnum.VIDEO.getCode()).equals(farmRecordsFile.getType2())){
                    JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                    List<String> list = jsonArray.toJavaList(String.class);
                    videoList = list;
                }
            }
        }
        //设置图片
        if (picList != null && picList.size() > 0){
            farmRecordsDrugs.setPicList(picList);
        }
        //设置视频
        if (videoList != null && videoList.size() > 0){
            farmRecordsDrugs.setVideoList(videoList);
        }

        return farmRecordsDrugs;
    }

    /**
     * 按条件查询(牛)
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    @Override
    public PageInfo<FarmRecordsDrugs> selectBullByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsDrugsMapper == null){
                throw new OPServerException("farmRecordsDrugsMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsDrugs> list = farmRecordsDrugsMapper.selectByMap(map);
            if (list.size() > 0){
                this.setPicOrVideoList(list);
            }
            return new PageInfo<FarmRecordsDrugs>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 新建一条记录 (暂存状态下)
     * @param farmRecordsDrugs
     * @param toStatus
     * @return  long 返回插入数据的id
     */
    @Override
    public Long createOne(LoginInfo loginInfo,FarmRecordsDrugs farmRecordsDrugs, Integer toStatus) {
        int id = 0;
        try {
            if (farmRecordsDrugsMapper == null){
                throw new OPServerException("farmRecordsDrugsMapper 为null,请检查");
            }
            String jsonBefore = JsonUtil.toJsonString(farmRecordsDrugs);

            Integer fromStatus = farmRecordsDrugs.getStatus();

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "SSY";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsDrugsMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsDrugs.setNumber(number);

            farmRecordsDrugs.setProvince_id(loginInfo.getProvinceId());
            farmRecordsDrugs.setCity_id(loginInfo.getCityId());
            farmRecordsDrugs.setRegion_id(loginInfo.getRegionId());
            farmRecordsDrugs.setStreet_id(loginInfo.getStreetId());
            farmRecordsDrugs.setVillage_id(loginInfo.getVillageId());

            farmRecordsDrugs.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            //todo 单据从状态到状态
            if (fromStatus == 0 && toStatus == null) {
                //直接暂存
                farmRecordsDrugsMapper.createOne(farmRecordsDrugs);
            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
                //直接提交
                farmRecordsDrugs.setStatus(toStatus);
                farmRecordsDrugsMapper.createOne(farmRecordsDrugs);
            }

            if (farmRecordsDrugs.getId() != 0) {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.DRUG.getCode(),farmRecordsDrugs.getPicList(),farmRecordsDrugs.getVideoList(),Long.valueOf(farmRecordsDrugs.getId()));
            }

            /*//todo 生成政府操作记录
            String jsonAfter = JsonUtil.toJsonString(farmRecordsDrugs);
            sysLogsService.createLogs(LogsEnum.ADD,
                    FarmRecordsTableEnum.FARM_RECORDS_DRUGS.getTableName(),
                    farmRecordsDrugs.getId().toString(),
                    jsonBefore,
                    jsonAfter,
                    loginInfo.getId());*/

            return farmRecordsDrugs.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL,HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 更新一条记录 (根据id或者number)
     * @param farmRecordsDrugs
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsDrugs farmRecordsDrugs,Integer toStatus) {
        try {
            if (farmRecordsDrugsMapper == null){
                throw new OPServerException("farmRecordsDrugsMapper 为null,请检查");
            }
            farmRecordsDrugs.setStatus(toStatus);
            farmRecordsDrugs.setUpdated_at(new Date());
            Integer con = farmRecordsDrugsMapper.updateByPrimaryKeySelective(farmRecordsDrugs);

            farmRecordsFileService.updatePicOrVideoByRelevanceId(FarmRecordsFileEnum.DRUG.getCode(),farmRecordsDrugs.getPicList(),farmRecordsDrugs.getVideoList(),Long.valueOf(farmRecordsDrugs.getId()));

            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    /**
     * 根据id删除记录
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Long id) {
        Long userId = UserUtil.getUserId();

        FarmRecordsDrugs drugs = farmRecordsDrugsMapper.selectByPrimaryKey(id);
        String jsonBefore = JsonUtil.toJsonString(drugs);

        FarmRecordsDrugs farmRecordsDrugs = new FarmRecordsDrugs();
        farmRecordsDrugs.setId(id);
        farmRecordsDrugs.setDelete_flag(FarmRecordsNumberStatus.INVALID.getCode());
        farmRecordsDrugs.setUpdated_at(new Date());
        int con = farmRecordsDrugsMapper.updateByPrimaryKeySelective(farmRecordsDrugs);

        String jsonAfter = JsonUtil.toJsonString(drugs);
        sysLogsService.createLogs(LogsEnum.DELETE, FarmRecordsTableEnum.FARM_RECORDS_DRUGS.getTableName(),drugs.getId().toString(),jsonBefore,jsonAfter,userId);

        return con == 0 ? false : true;
    }

    @Override
    public PageInfo<FarmRecordsDrugs> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null) {
            map.put("status",status);
        }

        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());
        map.put("farm_id",farmId);

        List<FarmRecordsDrugs> farmRecordsDrugsList = farmRecordsDrugsMapper.selectListByStatus(map);

        if (farmRecordsDrugsList.size() > 0){
            this.setPicOrVideoList(farmRecordsDrugsList);
        }

        return new PageInfo<FarmRecordsDrugs>(farmRecordsDrugsList);
    }

    /**
     * 根据养殖场id和时间区间获取兽药次数
     * @param farmId
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public Integer selectCountByFarmId(Long farmId, Date startDate, Date endDate) {
        Map<String,Object> map = Maps.newHashMap();
        if (farmId != null) {
            map.put("farmId",farmId);
        }
        if (startDate != null) {
            map.put("startDate",startDate);
        }
        if (endDate != null) {
            map.put("endDate",endDate);
        }
        Integer count = farmRecordsDrugsMapper.selectQuantityByFarmId(map);
        return count;
    }
}
